﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;

namespace SuperX.Common.Respository
{
    // 
    public class IPEndPointConverter : JsonConverter
    {
        // 
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(IPEndPoint);
        }

        //
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            IPEndPoint ipendPoint = (IPEndPoint)value;
            writer.WriteStartObject();
            writer.WritePropertyName("Address");
            serializer.Serialize(writer, ipendPoint.Address);
            writer.WritePropertyName("Port");
            writer.WriteValue(ipendPoint.Port);
            writer.WriteEndObject();
        }

        // 
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject jobject = JObject.Load(reader);
            IPAddress address = jobject["Address"].ToObject<IPAddress>(serializer);
            int port = Extensions.Value<int>(jobject["Port"]);
            return new IPEndPoint(address, port);
        }
    }
}
